package com.stary.pay.unionpay;

import com.stary.pay.unionpay.api.DefaultUnionpayClient;
import com.stary.pay.unionpay.api.UnionpayApiException;
import com.stary.pay.unionpay.api.UnionpayClient;
import com.stary.pay.unionpay.api.util.StringUtils;
import com.stary.pay.unionpay.api.util.UnionpayUtils;
import com.stary.pay.unionpay.config.IUnionpayConfig;

/**
 * <p>初始化银联请求客户端</p>
 * @author stary {@link stary1993@qq.com}
 * @since 2019-7-5
 */
public class InitUnionpayClient {
	/**
	 * 银联配置接口
	 */
	private IUnionpayConfig unionpayConfig;
			
	public InitUnionpayClient() {
		super();
	}
	
	public InitUnionpayClient(IUnionpayConfig unionpayConfig) {
		super();
		this.unionpayConfig = unionpayConfig;
	}

	public IUnionpayConfig getUnionpayConfig() {
		return unionpayConfig;
	}

	public void setUnionpayConfig(IUnionpayConfig unionpayConfig) {
		this.unionpayConfig = unionpayConfig;
	}

	/**
	 * 创建客户端
	 * @return {@link UnionpayClient}
	 * @throws UnionpayApiException 
	 */
	public UnionpayClient build() throws UnionpayApiException {
		UnionpayClient unionpayClient = null;
		if (StringUtils.isEmpty(unionpayConfig.merId())
				|| StringUtils.isEmpty(unionpayConfig.rootCertFile())
				|| StringUtils.isEmpty(unionpayConfig.middleCertFile())
				|| StringUtils.isEmpty(unionpayConfig.signCertFile())
				|| StringUtils.isEmpty(unionpayConfig.encryptCertFile())) {
			throw new UnionpayApiException("unionpay config merId or rootCertFile or middleCertFile or signCertFile or encryptCertFile must not null.");			
		}
		if (unionpayConfig.isTest()) {
			unionpayClient = new DefaultUnionpayClient(unionpayConfig.merId(), unionpayConfig.accessType(), 
							unionpayConfig.rootCertFile(), unionpayConfig.middleCertFile(), unionpayConfig.signCertFile(), unionpayConfig.encryptCertFile());
		} else {
			if (StringUtils.isEmpty( unionpayConfig.signCertPwd()) || StringUtils.isEmpty(unionpayConfig.secureKey())) {
				throw new UnionpayApiException("unionpay config signCertPwd or secureKey must not null");			
			}
			unionpayClient = new DefaultUnionpayClient(unionpayConfig.merId(), unionpayConfig.accessType(), 
							unionpayConfig.rootCertFile(), unionpayConfig.middleCertFile(), unionpayConfig.signCertFile(), unionpayConfig.signCertPwd(), unionpayConfig.encryptCertFile(), unionpayConfig.secureKey());
		}
		// 初始化证书
		unionpayClient.initCerts();
		UnionpayUtils.getLogger().info("build UnionpayClient succeed");
		return unionpayClient;
	}

}
